#include "mid/widgets/button.h"
#include "hardware/lcd_init.h"
#include "hardware/lcd.h"
#include "mid/printf.h"
#include "app/text.h"
#include "mid/utils.h"

#include <string.h>

Button BuildButton(int x, int y, int w, int h, const char* text, uint16_t textColor, uint16_t bgColor)
{
    Button btn;
    MoveTo(&btn, x, y);
    Resize(&btn, w, h);
    UpdateText(&btn, text);
    SetTextColor(&btn, textColor);
    SetBgColor(&btn, bgColor);
    return btn;
}

void MoveTo(Button *btn, int x, int y)
{
    btn->x = x;
    btn->y = y;
}

void Resize(Button *btn, int w, int h)
{
    btn->w = w;
    btn->h = h;
}

void Select(Button *btn, int selected)
{
    btn->selected = selected;
}

void UpdateText(Button *btn, char *text)
{
    btn->text = text; // text should hold util button destroyed
}

void SetColor(Button *btn, uint32_t color)
{
    btn->textColor = color;
}

void SetTextColor(Button *btn, uint16_t color)
{
    btn->textColor = color;
}

void SetBgColor(Button *btn, uint16_t color)
{
    btn->bgColor = color;
}

void RenderButton(Button *btn)
{
    int strW = StrWidth(btn->text);

    //绘制背景矩形
    int sx = btn->x - btn->w / 2;
    int sy = btn->y - btn->h / 2;
    int ex = btn->x + btn->w / 2;
    int ey =  btn->y + btn->h / 2;
    LCD_Fill(sx, sy, ex, ey, btn->bgColor);
    if (strW > 0)
        LCD_ShowStringV2(btn->x - strW / 2, btn->y - FONT_SIZE / 2, btn->text, btn->textColor, btn->bgColor, FONT_SIZE, 1);
    uint16_t rectColor = btn->bgColor;
    if (btn->selected == 1)
        rectColor = btn->textColor;
    for (int i = 1; i <= 3; i++)
    {
        LCD_DrawRectangle(sx - i, sy - i, ex + i - 1, ey + i - 1, rectColor);
    }
}
